﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Text;

namespace MenusSample
{
    public class MenusContext : DbContext
    {
        //连接字符串
        private const string ConnectionString = @"server=(localdb)\MSSQLLocalDb;" +
            "Database=MenuCards;Trusted_Connection=True";
        //Menu数据集
        public DbSet<Menu> Menus { get; set; }
        //MenuCard数据集
        public DbSet<MenuCard> MenuCards { get; set; }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            //设置数据库连接字符串
            optionsBuilder.UseSqlServer(ConnectionString);
           // optionsBuilder.UseSqlServer(ConnectionString, options => options.MaxBatchSize(1));
        }


        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //设置模式名为mc
            base.OnModelCreating(modelBuilder);
            modelBuilder.HasDefaultSchema("mc");
            //应用MenuCardConfiguration选项，设置表属性
            modelBuilder.ApplyConfiguration(new MenuCardConfiguration());
            //应用MenuConfiguration，设置表属性
            modelBuilder.ApplyConfiguration(new MenuConfiguration());

            //.netcore2.0后提供了新选项，可以为每个类设计配置类
            //modelBuilder.Entity<T>可设置表的SQL属性
            //modelBuilder.Entity<MenuCard>()
            //    .ToTable("MenuCards")
            //    .HasKey(c => c.MenuCardId);
            //modelBuilder.Entity<MenuCard>()
            //    .Property(c => c.MenuCardId)
            //    .ValueGeneratedOnAdd();
            //modelBuilder.Entity<MenuCard>()
            //    .Property(c => c.Title)
            //    .HasMaxLength(50);

            //定义一对多映射.HasMany .WithOne会定义一对多关系
            ////modelBuilder.Entity<MenuCard>()
            ////    .HasMany(c => c.Menus)
            ////    .WithOne(m => m.MenuCard);

            //modelBuilder.Entity<Menu>()
            //    .ToTable("Menus")
            //    .HasKey(m => m.MenuId);

            //modelBuilder.Entity<Menu>()
            //    .Property(m => m.MenuId)
            //    .ValueGeneratedOnAdd();

            //modelBuilder.Entity<Menu>()
            //    .Property(m => m.Text)
            //    .HasMaxLength(120);

            //modelBuilder.Entity<Menu>()
            //    .Property(m => m.Price)
            //    .HasColumnType("Money");

            //.HasOne WithMany定义一对多关系
            //modelBuilder.Entity<Menu>()
            //    .HasOne(m => m.MenuCard)
            //    .WithMany(m => m.Menus)
            //    .HasForeignKey(m => m.MenuCardId);
        }
    }
}
